<template>
  <div class="w-full p-6">
    <!-- 组件列表容器 -->
    <div class="components-container space-y-4" @dragover.prevent="handleCanvasDragOver"
      @dragenter.prevent="handleCanvasDragEnter" @dragleave="handleCanvasDragLeave" @drop.prevent="handleCanvasDrop" @click.stop>
      <!-- 遍历渲染每个组件 -->
      <div v-for="(component, index) in safeComponents" :key="getItemKey(component)"
        class="canvas-component-wrapper relative"  @drop.prevent="handleComponentDrop($event, index)"
        @mouseenter="hoveredIndex = index" @mouseleave="hoveredIndex = -1">
        <!-- 组件操作工具栏 -->
        <div v-if="isEditable && hoveredIndex === index"
          class="absolute right-2 top-2 flex gap-2 bg-white p-1 rounded-md shadow-md z-20">
          <button
            class="w-7 h-7 rounded-full text-gray-500 hover:bg-primary hover:text-white"
            @click.stop="moveComponentUp(index)" :disabled="index === 0" :title="index === 0 ? '已到顶部' : '上移'">
            <i class="fa fa-arrow-up text-xs"></i>
          </button>
          <button
            class="w-7 h-7 rounded-full text-gray-500 hover:bg-primary hover:text-white"
            @click.stop="moveComponentDown(index)" :disabled="index === safeComponents.length - 1"
            :title="index === safeComponents.length - 1 ? '已到底部' : '下移'">
            <i class="fa fa-arrow-down text-xs"></i>
          </button>
          <button class="w-7 h-7 rounded-full text-gray-500 hover:bg-primary hover:text-white"
            @click.stop="handleComponentSettings(index)" title="设置">
            <i class="fa fa-cog text-xs"></i>
          </button>
          <button class="w-7 h-7 rounded-full text-gray-500 hover:bg-primary hover:text-white"
            @click.stop="handleComponentDelete(index)" title="删除">
            <i class="fa fa-trash text-xs"></i>
          </button>
        </div>

        <!-- 组件内容容器 -->
        <div class="component-content-wrapper min-h-[40px]">
          <component :is="component.config.component" v-bind="component.props" :children="component.children || []"
            @hook:mounted="handleComponentMounted(index)" @hook:updated="handleComponentUpdated(index)"
            v-on="getComponentEventListeners(component, index)" ref="componentInstances[index]"
            class="component-content w-full"></component>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, markRaw } from 'vue';

export default {
  props: {
    components: {
      type: Array,
      default: () => []
    },
    children: {
      type: Array,
      default: () => []
    },
    isEditable: {
      type: Boolean,
      default: true
    },
    availableComponents: {
      type: Array,
      default: () => []
    }
  },
  emits: [
    'component-select', 'component-delete', 'component-update',
    'component-mounted', 'components-reordered', 'request-component-settings',
    'update:components', 'component-added', 'child-event'
  ],
  setup(props, { emit }) {
    const componentInstances = ref([]);
    
    // 跟踪当前鼠标悬停的组件索引
    const hoveredIndex = ref(-1);

    // 确保组件列表始终有效
    const safeComponents = computed(() => {
      if (!Array.isArray(props.components)) {
        console.warn('components必须是一个数组，已使用默认空数组');
        return [];
      }
      return props.components.filter(item => {
        if (!item || typeof item !== 'object') return false;
        if (!item.config || !item.config.component) {
          console.warn('组件缺少必要的config信息');
          return false;
        }
        item.config.component = markRaw(item.config.component);
        return true;
      });
    });

    // 获取唯一标识
    const getItemKey = (element) => {
      if (element && element.id) {
        return element.id;
      }
      return `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    };
    
    // 处理组件拖放
    const handleComponentDrop = (e, index) => {
      const targetComponent = safeComponents.value[index];
      if (targetComponent.config.isContainer) {
        emit('component-added', index);
      }
    };

    // 移动现有组件
    const moveExistingComponent = (sourceIndex, targetIndex) => {
      if (sourceIndex === targetIndex) return;

      const newComponents = [...safeComponents.value];
      const [movedComponent] = newComponents.splice(sourceIndex, 1);
      newComponents.splice(targetIndex, 0, movedComponent);

      emit('update:components', newComponents);
      emit('components-reordered', {
        oldIndex: sourceIndex,
        newIndex: targetIndex,
        components: newComponents
      });
    };

    // 上移组件
    const moveComponentUp = (index) => {
      if (index <= 0) return;
      moveExistingComponent(index, index - 1);
    };

    // 下移组件
    const moveComponentDown = (index) => {
      if (index >= safeComponents.value.length - 1) return;
      moveExistingComponent(index, index + 1);
    };

    // 处理嵌套组件的事件
    const handleNestedComponentEvent = (parentIndex, event) => {
      // 对于设置请求，需要将事件继续向上传递给App.vue
      if (event.type === 'request-child-settings') {
        emit('request-component-settings', {
          index: parentIndex,
          path: event.data.path,
          childComponent: event.data.childComponent
        });
      } else if (event.type === 'local-move-child' || event.type === 'local-delete-child') {
        // 对于其他类型的事件，也向上传递
        emit('child-event', {
          parentIndex,
          event
        });
      } else if (event.type === 'request-add-child') {
        // 处理添加子组件的请求
        emit('child-event', {
          parentIndex,
          event
        });
      }
    };

    // 获取组件事件监听器
    const getComponentEventListeners = (component, index) => {
      const listeners = {};

      if (props.isEditable) {
        listeners.click = (e) => {
          e.stopPropagation();
        };
      }

      // 添加对child-event的监听，用于处理嵌套组件的事件
      listeners['child-event'] = (event) => {
        handleNestedComponentEvent(index, event);
      };

      return listeners;
    };


    const handleComponentMounted = (index) => {
      emit('component-mounted', {
        index,
        instance: componentInstances.value[index],
        componentKey: safeComponents.value[index].config.componentKey
      });
    };

    const handleComponentUpdated = (index) => {
      emit('component-update', {
        index,
        props: safeComponents.value[index].props
      });
    };

    const handleComponentDelete = (index) => {
      emit('component-delete', index);
    };

    const handleComponentSettings = (index) => {
      emit('request-component-settings', index);
    };

    return {
      componentInstances,
      safeComponents,
      getItemKey,
      moveComponentUp,
      moveComponentDown,
      getComponentEventListeners,
      handleComponentMounted,
      handleComponentUpdated,
      handleComponentDelete,
      handleComponentSettings,
      handleComponentDrop,
      hoveredIndex
    };
  }
};
</script>

<style scoped>
.components-wrapper {
  width: 100%;
}

.components-container {
  transition: all 0.2s ease;
}

.canvas-component-wrapper {
  padding: 1rem;
  margin: 0.5rem 0;
  position: relative;
  transition: all 0.2s ease;
}

.component-highlight {
  background-color: rgba(22, 93, 255, 0.05);
  border-radius: 0.5rem;
  border: 1px dashed #165DFF;
}

.component-content-wrapper {
  width: 100%;
  transition: all 0.2s ease;
}

.component-content {
  width: 100%;
}

.shadow-md {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
</style>